package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishFlavorMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     *
     * @param dishDto
     */
    //多表操作添加事务管理
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void addDish(DishDto dishDto) {
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        //清除redis所有缓存
        //Set keys = redisTemplate.keys("dish_*");
        //redisTemplate.delete(keys);
        //精确清除单个
        redisTemplate.delete(key);
        //mybatis插入成功后会将 雪花算法得到的id 赋值给实例所映射的属性
        dishMapper.insert(dishDto);
        //获取菜品id
        Long id = dishDto.getId();
        saveFlavor(dishDto, id);
        redisTemplate.opsForSet().add("set2",dishDto.getImage());
    }

    /**
     * 修改菜品数据回显
     *
     * @param id
     * @return
     */
    @Override
    public DishDto queryDishById(Long id) {
        //根据id查询菜品
        Dish dish = dishMapper.selectById(id);
        DishDto dishDto = new DishDto();
        //克隆属性
        BeanUtils.copyProperties(dish, dishDto);
        //根据菜品id查询口味集合
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId, id);
        List<DishFlavor> dishFlavors = dishFlavorMapper.selectList(lqw);

        dishDto.setFlavors(dishFlavors);

        return dishDto;
    }

    /**
     * 菜品分页条件查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public Page<DishDto> getDishPage(int page, int pageSize, String name) {
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        lqw.orderByDesc(Dish::getUpdateTime);

        Page<Dish> dishPage = new Page<>(page, pageSize);
        dishMapper.selectPage(dishPage, lqw);
        //List<Dish> records = dishPage.getRecords();
        //
        //List<Dish> dishList = records.stream().map(item -> {
        //  Long categoryId = item.getCategoryId();
        //  Category category = categoryService.getById(categoryId);
        //  item.setCategoryName(category.getName());
        //  return item;
        //  }).collect(Collectors.toList());
        Page<DishDto> dishDtoPage = new Page<>();
        //dishDtoPage克隆dishPage的属性,排除records属性
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");
        List<Dish> records = dishPage.getRecords();
        List<DishDto> dishDtoList = records.stream().map(item -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryMapper.selectById(categoryId);
            dishDto.setCategoryName(category.getName());
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(dishDtoList);
        return dishDtoPage;
    }

    /**
     * 删除菜品
     *
     * @param ids
     */
    @Override
    public void deleteDish(List<Long> ids) {
        //清除redis所有缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        //先删除口味表数据
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.in(DishFlavor::getDishId, ids);
        dishFlavorMapper.delete(lqw);
        //删除菜品
        List<Dish> dishes = dishMapper.selectBatchIds(ids);
        for (Dish dish : dishes) {
            Integer status = dish.getStatus();
            if (status == 1) {
                throw new CustomException("菜品正在销售");
            }
        }
        dishMapper.deleteBatchIds(ids);
    }

    /**
     * 修改菜品状态(启售,禁售)
     *
     * @param status
     * @param ids
     */
    @Override
    public void dishStatusByStatus(Integer status, List<Long> ids) {
        //清除redis所有缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        ids.stream().map(item -> {
            Dish dish = new Dish();
            dish.setId(item);
            dish.setStatus(status);
            return dish;
        }).forEach(dishMapper::updateById);
    }

    /**
     * 修改菜品
     *
     * @param dishDto
     */
    @Override
    public void editDish(DishDto dishDto) {
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        //清除redis所有缓存
        //Set keys = redisTemplate.keys("dish_*");
        //redisTemplate.delete(keys);
        //精确清除单个
        redisTemplate.delete(key);
        dishMapper.updateById(dishDto);
        //删除口味表数据
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        Long dishId = dishDto.getId();
        lqw.eq(DishFlavor::getDishId, dishId);
        dishFlavorMapper.delete(lqw);
        //跟新口味表
        saveFlavor(dishDto, dishId);
    }

    /**
     * 根据条件查询菜品
     *
     * @return
     */
    @Override
    public List<DishDto> queryDishList(Dish dish) {
        List<DishDto> dishDtoList = null;
        //从redis中获取数据
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        //如果redis中有数据直接返回
        if (dishDtoList != null) {
            log.info("redis中存在,从redis中获取数据");
            return dishDtoList;
        }
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        lqw.like(StringUtils.isNotEmpty(dish.getName()), Dish::getName, dish.getName());
        //只查询启售菜品
        lqw.ne(dish.getStatus() == null, Dish::getStatus, 0);
        //排序条件
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> dishList = dishMapper.selectList(lqw);
        //根据菜品id查询口味
        dishDtoList = dishList.stream().map(dish1 -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish1, dishDto);
            Long id = dish1.getId();
            LambdaQueryWrapper<DishFlavor> flavorLqw = new LambdaQueryWrapper<>();
            flavorLqw.eq(DishFlavor::getDishId, id);
            List<DishFlavor> dishFlavors = dishFlavorMapper.selectList(flavorLqw);
            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());

        //如果没有就查询数据库,保存到redis中(60分钟超时)
        redisTemplate.opsForValue().set(key, dishDtoList, 60, TimeUnit.MINUTES);
        log.info("成功保存到redis中");
        return dishDtoList;
    }

    /**
     * 根据菜品id批量新增口味
     *
     * @param dishDto
     * @param dishId
     */
    private void saveFlavor(DishDto dishDto, Long dishId) {
        List<DishFlavor> dishFlavors = dishDto.getFlavors();
        dishFlavors.stream().map(dishFlavor -> {
            dishFlavor.setDishId(dishId);
            return dishFlavor;
        }).forEach(dishFlavorMapper::insert);
    }
}
